package ixRedis

import (
	"errors"
	"strings"
	"sync"

	"github.com/garyburd/redigo/redis"
)

// Client Redis 客户端
type Client struct {
	pool   *redis.Pool
	config *Config
	mu     sync.RWMutex
	closed bool
}

// Close 关闭 Redis 客户端
func (c *Client) Close() error {
	if c == nil {
		return nil
	}

	c.mu.Lock()
	defer c.mu.Unlock()

	if c.closed {
		return nil
	}

	c.closed = true
	return c.pool.Close()
}

// IsClosed 检查客户端是否已关闭
func (c *Client) IsClosed() bool {
	if c == nil {
		return true
	}

	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.closed
}

// getConn 获取连接
func (c *Client) getConn() (redis.Conn, error) {
	if c.IsClosed() {
		return nil, errors.New("client is closed")
	}

	conn := c.pool.Get()
	if conn.Err() != nil {
		return nil, conn.Err()
	}

	return conn, nil
}

// buildKey 构建带前缀的键
func (c *Client) buildKey(key string) string {
	if c.config.KeyPrefix != "" {
		if strings.Contains(c.config.KeyPrefix, ":") {
			return c.config.KeyPrefix + key
		}
		return c.config.KeyPrefix + ":" + key
	}
	return key
}
